package cn.itsource.config.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PetConstant;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.vo.LoginVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;

//@Component //spring管理
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;



    /**
     * 进入目标方法（Controller的方法）之前之前，false：拦截  true：放行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("----------------"+request.getRequestURI());

        //告诉浏览器我返回的数据按json来解析
        response.setContentType("application/json;charset=utf-8");

        //1.从request获取token信息
        String token = request.getHeader("token");
        //2.如果token不存在，重新登录
        if (StrUtil.isBlank(token)){
            return extracted(response);
        }
        //3.拿到token，从redis里面获取登录信息
        LoginVo vo = redisService.getKeyObjectValue(token, LoginVo.class);

        //3.1如果没有获取到，重新登录
        if (vo == null){
            //ALT+SHIFT+M
            return extracted(response);
        }

        //4.重点：一定要刷新redis的登录信息，重新计时30min
        redisService.setStringKeyAndValue(token,vo,30);
        return true;
    }

    /**
     * 登录错误的公共返回
     * @param response
     * @return
     * @throws IOException
     */
    private boolean extracted(HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        //1001
        AjaxResult loginResult = AjaxResult.createError(PetConstant.SYSTEM_LOGIN_TIMOUT, "给劳资去登录");

        writer.write(JSONObject.toJSONString(loginResult));
        //拦截
        return false;
    }
}
